# !/usr/bin/evn python3
# -*- coding: utf-8 -*-
# File Name: orders.py
# Created Date: 2017-12-12 10:16:23

from flask import g, request
from app.models.order import Order
from timeit import Timer, timeit

def orders():
    items, page = Order.model_search(**request.args.to_dict())
    return {'orders': [item.to_json() for item in items], 'page': page, 'msg': "ok", "code": 200}


def create_order():
    args = request.form.to_dict()
    args["user_id"] = g.current_user["id"]
    args["account_id"]= g.current_user.get("account_id", 1)
    ok, order = Order.create_order(**args)
    if ok:
        return {
                'order': order.to_json(),
                "msg": "ok",
                "code": 200
                }
    else:
        return {
                "msg": order,
                "code": 422
                }


def update_order(id):
    #可修改的参数
    args = request.form.to_dict()
    order = Order.query.filter_by(id=id).first()
    if order is None:
        return {"msg": "订单没有找到", "code": 404}
    ok, order = order.update_order(**args)
    if ok:
        return {"order": order.to_json(), "msg": "ok", "code": 200}
    else:
        return {"msg": order, "code": 422}
        
    
